local skynet = require "skynet"

local CMD = {}
local TableFrameSink={}
local TableObj = nil
local Manager = nil
local GAME_ID = 2001
local GameNum=nil
local GamePaiShu=nil
local IsAdvise=nil
local itableframe=nil

function send_data(addr,msg)
    skynet.send(addr,"lua","send_data",msg)
end

function TableFrameSink.GetPlayerTableChair(Player)
    local play_id,chair_id,tabel_id = skynet.call(Manager,"lua","GetPlayerTableChair",Player)
    return play_id , chair_id , tabel_id
end


function TableFrameSink.BroadCastGameStart()
    for k,chair in pairs(TableObj.m_pChairs) do
        local msg = string.pack(">I2>I2",303,2004)
        send_data(chair.Player.nAgentAddr,msg)
        local gameStartDataMsg = string.pack(">I2>I2<I2<I2<I2<I1<I1<I1<I1<I1<I1<I1<I1<I2", 303, 2771,1,1,1,0x25,0x25,0x25,0x25
        ,0x25,0x25,0x25,0x25,1)
        local puke=string.pack("<I1<I1<I1<I1<I1",0,0,0x25,0x25,0)
        puke=puke..string.pack("<I1<I1<I1<I1<I1",0,0,0x25,0x25,0x25)
        puke=puke..string.pack("<I1<I1<I1<I1<I1",0,0,0x25,0x25,0x25)
        puke=puke..string.pack("<I1<I4<I4<I4",0,0,0,0)
        gameStartDataMsg=gameStartDataMsg..puke..string.pack("<I2",0)
        send_data(chair.Player.nAgentAddr, gameStartDataMsg)
        skynet.error("[tableframe]",chair.Player.nPlayerId,chair.Player.nAgentAddr)
    end
end


function CMD.SetTableData(nMaxPlayerCount,nDiFen,nMa,nFangPaoOrZiMo,nDianPaoMaOrZiMoMa,nKeQiangGang,externData)
    local makeroommsg="摆牌八张 底分:"..nDiFen.." 马:"..nMa
    GameNum,GamePaiShu,IsAdvise=string.unpack("I4I4I4",externData,1)
    skynet.error("[tableframe]",GameNum,GamePaiShu,IsAdvise)
    return makeroommsg
end

function CMD.OnEventGameStart(Tabel,itableframe_)
    TableObj = Tabel
    itableframe=itableframe_
    TableFrameSink.BroadCastGameStart()
    TableObj.m_wCurJu=TableObj.m_wCurJu+1
    for i=1,TableObj.m_nPlayerCount do
        TableObj.m_pChairs[i].nAnGang=125
        TableObj.m_pChairs[i].nMingGang=250
    end
    skynet.call(itableframe,"lua","ConcluedGame",TableObj)
end


function CMD.OnGameMessage(scmd,smsg,Player)
     skynet.error("[tableframe]",scmd)
end

function CMD.OnSitDownSucess(Player)
    local msg=string.pack(">I2>I2<I4<I4",303,2070,GAME_ID,GameNum)
    send_data(Player.nAgentAddr, msg)
end


function CMD.ConcluedGame()
    skynet.call(itableframe,"lua","ConcluedGameFriend",TableObj)
end

skynet.start(function()
    skynet.error("tableframe server start...")
	skynet.dispatch("lua", function(_,_, command, ...)
		local f  =  CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)
    Manager = skynet.localname(".manager")
    math.randomseed(os.time())
end)